package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * @Author：fish
 * @Date：2023/4/10 14:55
 */
@WebServlet("/delart")
public class DelArticleServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "未知错误！";
        int data = 0;
        Integer aid = null;
        //登录权限验证，并且验证归属人（自己只能删除自己的文章）
        UserInfo userInfo = SessionUtils.getLoginUser(req);
        if (userInfo != null) {
            //1.先得到前端的参数并效验
            String aidStr = req.getParameter("aid");
            if (!StrUtil.isBlank(aidStr)) {
                aid  = Integer.valueOf(aidStr);
            }
            if (aid != null && aid > 0) {
                //参数有效
                //删除文章
                //2.连接数据库
                Connection connection = DBUtils.getConnection();
                String sql = "delete from article where aid=? and uid=?";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1,aid);
                statement.setInt(2,userInfo.getUid());
                data = statement.executeUpdate();
                //关闭资源
                DBUtils.close(null,statement,connection);
                msg = "";
            }else {
                msg = "非法参数！";
            }
        }else {
            msg = "请先登录！";
        }
        //3.将结果返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }
}
